package com.dl698.sessionlayer.hdlc;

/**
 * HDLC地址对类
 * 封装客户端和服务器地址
 * 
 * @author wind
 * @version 1.1.1
 */
public class HdlcAddressPair {

    private byte[] cliAddr = null;
    private HdlcAddress srvAddr = null;

    /**
     * 构造函数
     * 
     * @param srvAddr 服务器地址
     * @param cliAddr 客户端地址
     */
    public HdlcAddressPair(HdlcAddress srvAddr, byte[] cliAddr) {
        this.cliAddr = cliAddr;
        this.srvAddr = srvAddr;
    }

    /**
     * 获取客户端地址
     * 
     * @return 客户端地址
     */
    public byte[] getCliAddr() {
        if (cliAddr != null) {
            return cliAddr;
        } else {
            throw new RuntimeException("cliAddr is null");
        }
    }

    /**
     * 获取服务器地址
     * 
     * @return 服务器地址
     */
    public HdlcAddress getSrvAddr() {
        if (srvAddr != null) {
            return srvAddr;
        } else {
            throw new RuntimeException("srvAddr is null");
        }
    }

    /**
     * 切换地址对
     * 
     * @return 切换后的地址对
     */
    public HdlcAddressPair switchedPair() {
        if (srvAddr != null && cliAddr != null) {
            return new HdlcAddressPair(srvAddr, cliAddr);
        } else {
            throw new RuntimeException("srvAddr or cliAddr is null");
        }
    }

    @Override
    public String toString() {
        if (cliAddr != null && srvAddr != null) {
            return srvAddr.toString() + ":" + bytesToHex(cliAddr);
        } else {
            return "cliAddr or srvAddr is null";
        }
    }

    /**
     * 将字节数组转换为十六进制字符串
     * 
     * @param bytes 字节数组
     * @return 十六进制字符串
     */
    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }
}